package com.ruochen.common.base;

import android.os.Bundle;
import android.view.KeyEvent;

import androidx.databinding.ViewDataBinding;

/**
 * @描述: BaseMvpActivity
 * @作者: 宋俊 SongJun
 * @时间: 2016/11/10 12:13
 * @版权: 云腾科技
 * @官网: http://www.gzytkj.net/
 */
public abstract class BaseMvpActivity<VB extends ViewDataBinding, P extends BasePresenter> extends BaseActivity<VB> {

    protected P mvpPresenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mvpPresenter = createPresenter();
        super.onCreate(savedInstanceState);
    }

    protected abstract P createPresenter();

    public P getMvpPresenter() {
        return mvpPresenter;
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (mvpPresenter == null){
            mvpPresenter = createPresenter();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if(isCancelRequestOnClickBack()){
                if(mSVProgressHUD != null && mSVProgressHUD.isShow()){
                    mvpPresenter.cleanAllRequest();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void removeCallBack(ApiCallback callback) {
        if(mvpPresenter != null){
            mvpPresenter.removeCallBack(callback);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mvpPresenter != null) {
            mvpPresenter.detachView();
            mvpPresenter = null;
        }
    }

}
